package com.example.h5server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.h5server.model.User;
import com.example.h5server.repository.UserMapper;
import com.example.h5server.service.PhoneLoginService;
import com.example.h5server.utils.JwtUtils;
import com.example.h5server.utils.Result;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PhoneLoginServiceImpl implements PhoneLoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public Result<LoginAuthServiceImpl.LoginResponse> loginByPhone(String phone, String password) {
        // 验证手机号格式
        if (!isValidPhone(phone)) {
            return Result.error("请输入正确的手机号");
        }

        // 查找用户
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("phone", phone));

        // 用户不存在则自动创建
        if (user == null) {
            user = createNewUser(phone);
        }

        // 验证密码
        boolean isAuthenticated = checkPassword(password, user.getPassword());
        if (isAuthenticated) {
            String token = jwtUtils.generateToken(user.getId());
            LoginAuthServiceImpl.LoginResponse response = new LoginAuthServiceImpl.LoginResponse(user, token);
            return Result.success("登录成功", response);
        } else {
            return Result.error("密码错误");
        }
    }

    /**
     * 验证手机号格式
     */
    private boolean isValidPhone(String phone) {
        return phone != null && phone.matches("^1[3-9]\\d{9}$");
    }

    /**
     * 创建新用户
     */
    private User createNewUser(String phone) {
        User newUser = new User();
        newUser.setMobile(phone);
        newUser.setUsername("user_" + phone);
        // 设置默认密码
        String defaultPassword = BCrypt.hashpw("123456", BCrypt.gensalt());
        newUser.setPassword(defaultPassword);

        userMapper.insert(newUser);
        return userMapper.selectById(newUser.getId());
    }

    /**
     * 验证密码
     */
    private boolean checkPassword(String rawPassword, String encodedPassword) {
        try {
            return BCrypt.checkpw(rawPassword, encodedPassword);
        } catch (Exception e) {
            return false;
        }
    }
}
